﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;

namespace ObjectBakery.Adapters.Strategies
{
    public class ListToDataTableAdapter<T> : ListToDataTableAdapter
    {
        public ListToDataTableAdapter(IList list) : base(list, typeof(T)) { }
    }

    public class ListToDataTableAdapter: IAdapterStrategy<IList, DataTable>
    {
        Helpers.DataSyncHelper syncHelper = new Helpers.DataSyncHelper();

        //put in base
        Type type;


        public ListToDataTableAdapter(IList implementationObject, Type type)
        {
            this.implementationObject = implementationObject;
            this.type = type;
        }

        #region IAdapterStrategy<IList,DataTable> Members

        private IList implementationObject;

        public IList ImplementationObject
        {
            get { return implementationObject; }
            set { implementationObject = value; }
        }

        public ListToDataTableAdapter(IList implementationObject)
        {
            this.implementationObject = implementationObject;
        }

        public void Fill(DataTable table)
        {
            if (implementationObject.Count > 0)
                syncHelper.EnsureStructure(implementationObject[0], table.NewRow());

            table.Rows.Clear(); //drain existing
            ImplementationObject.Cast<object>().ToList().ForEach(item =>
            {
                if (item.GetType() == type)
                {
                    var row = table.NewRow();
                    syncHelper.Sync(item, row);
                    table.Rows.Add(row);
                }
            });
            
        }

        public void Flush(DataTable table)
        {
            table.Rows.Cast<DataRow>().ToList().ForEach(row =>
            {
                var inst = Activator.CreateInstance(type);

                //DynamicObject dynamicObject = new DynamicObject();
                //var inst = dynamicObject.CreateDuck(type);

                syncHelper.Sync(row, inst);
                ImplementationObject.Add(inst);
            });
        }

        #endregion
    }
}
